package com.company.堆栈队列;

import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;

/**
 * @author zhangjian
 * @data 2023/4/1
 * @Version 1.0
 * @DescripionAB2 栈的压入、弹出序列
 */
public class AB2栈压入弹出序列 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] pushA = Arrays.stream(input.nextLine().split(",")).mapToInt(Integer::parseInt).toArray();
        int[] popA = Arrays.stream(input.nextLine().split(",")).mapToInt(Integer::parseInt).toArray();
        boolean isPopOrder = isPopOrder(pushA, popA);
        System.out.println(isPopOrder);
    }

    public static boolean isPopOrder(int[] pushA, int[] popA) {

        boolean flag = false;
        int count = 0;
        Stack<Integer> stack = new Stack<>();
        Stack<Integer> tempStack = new Stack<>();

        int i = 0;
        int j = 0;
        // 当栈顶元素等于popA的第j个元素时，弹出栈顶元素
        while (i < pushA.length && tempStack.size() != pushA.length) {
            if (stack.isEmpty() || stack.peek() != popA[j]) {
                stack.push(pushA[i]);
                i++;
            } else {
                tempStack.push(stack.pop());
                j++;
            }
        }
        // 当栈stack不为空或者tempSatck为空时。将栈stack元素压入到tempStack栈中
        while (tempStack.isEmpty() || !stack.isEmpty()) {
            tempStack.push(stack.pop());
        }
        for (int k = popA.length - 1; k >= 0; k--) {
            if (!tempStack.isEmpty()) {
                if (popA[k] == tempStack.pop()) {
                    count++;
                }
            }
        }
        if (count == popA.length) {
            flag = true;
        }
        return flag;
    }

}
